package com.northpool.operator.common.json;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONPath;
import com.northpool.operator.annotation.InputParam;
import com.northpool.operator.annotation.InputParams;
import com.northpool.operator.annotation.OperatorInfo;
import com.northpool.operator.annotation.OutputParam;
import com.northpool.operator.annotation.OutputParams;
import com.northpool.operator.common.algorithm.OperatorTestBuild;
import com.northpool.operator.common.algorithm.TestParamBuilder;
import com.northpool.operator.param.ParamTool;
import com.northpool.operator.type.TypeEnum;
import com.northpool.operator.utils.StpOperatorHelper;

@OperatorInfo(
        ref = "JsonSetOperator",
        name = "Json数据填充",
        description = ""
)
@OutputParams({
        @OutputParam(ref = "execResult", name = "数据操作结果", type = TypeEnum.STRING)
})
public class JsonSetOperator extends StpOperatorHelper {

    @InputParams({
            @InputParam(ref = "jsonStr", name = "JSON字符串", desc = "JSON字符串,如: {\"name\":\"test\"}", required = true),
            @InputParam(ref = "exec", name = "表达式", desc = "JsonPath表达式,文档地址: http://northpool.work:6807/ZvVXBz6XYE", required = true),
            @InputParam(ref = "value", name = "替换值", desc = "根据JsonPath表达式替换对应的数据值", required = true),
    })
    public JsonSetOperator() {
    }

    public static void main(String[] args) throws Exception {
        OperatorTestBuild.execute(JsonSetOperator.class, TestParamBuilder.aBuilder()
                .param("jsonStr", "{\"name\":\"test\"}")
                .param("exec", "$.name")
                .param("value", "value")
                .build());
    }

    @Override
    public void execute(ParamTool paramTool) throws Exception {
        String jsonStr = paramTool.getStr("jsonStr");
        String exec = paramTool.getStr("exec");
        String value = paramTool.getStr("value");

        JSONObject jsonObject = JSON.parseObject(jsonStr);

        JSONPath jsonPath = new JSONPath(exec);
        jsonPath.set(jsonObject, value);

        this.result("execResult", jsonObject.toString());
    }

}
